<template>
    <div class="page-container">
        <h1 class="page-title">个人中心</h1>
        <div class="profile-container">
            <el-card class="profile-card" shadow="hover">
                <div class="user-header">
                    <el-avatar :size="80" class="user-avatar">
                        <el-icon><User /></el-icon>
                    </el-avatar>
                    <div class="user-info">
                        <h2>{{ userInfo.userName || '用户名' }}</h2>
                        <p>
                            {{
                                userInfo.role === 'ADMIN'
                                    ? '管理员'
                                    : userInfo.role === 'PSYCHOLOGIST'
                                    ? '心理医生'
                                    : '普通用户'
                            }}
                        </p>
                    </div>
                </div>

                <el-divider />

                <el-form
                    ref="formRef"
                    :model="form"
                    :rules="rules"
                    label-width="100px"
                    label-position="top"
                    class="profile-form"
                >
                    <el-form-item label="用户名" prop="userName">
                        <el-input
                            v-model="form.userName"
                            placeholder="请输入用户名"
                        />
                    </el-form-item>

                    <el-form-item label="账号" prop="accountId">
                        <el-input v-model="form.accountId" disabled />
                    </el-form-item>

                    <el-form-item label="邮箱" prop="email">
                        <el-input
                            v-model="form.email"
                            placeholder="请输入邮箱"
                        />
                    </el-form-item>

                    <el-form-item label="手机号" prop="phone">
                        <el-input
                            v-model="form.phone"
                            placeholder="请输入手机号"
                        />
                    </el-form-item>

                    <el-form-item>
                        <el-button
                            type="primary"
                            @click="updateProfile"
                            :loading="loading"
                            >保存修改</el-button
                        >
                    </el-form-item>
                </el-form>
            </el-card>

            <el-card class="password-card" shadow="hover">
                <template #header>
                    <div class="card-header">
                        <h2>修改密码</h2>
                    </div>
                </template>

                <el-form
                    ref="passwordFormRef"
                    :model="passwordForm"
                    :rules="passwordRules"
                    label-width="120px"
                    label-position="top"
                    class="password-form"
                >
                    <el-form-item label="当前密码" prop="currentPassword">
                        <el-input
                            v-model="passwordForm.currentPassword"
                            type="password"
                            placeholder="请输入当前密码"
                            show-password
                        />
                    </el-form-item>

                    <el-form-item label="新密码" prop="newPassword">
                        <el-input
                            v-model="passwordForm.newPassword"
                            type="password"
                            placeholder="请输入新密码"
                            show-password
                        />
                    </el-form-item>

                    <el-form-item label="确认新密码" prop="confirmPassword">
                        <el-input
                            v-model="passwordForm.confirmPassword"
                            type="password"
                            placeholder="请再次输入新密码"
                            show-password
                        />
                    </el-form-item>

                    <el-form-item>
                        <el-button
                            type="primary"
                            @click="updatePassword"
                            :loading="passwordLoading"
                            >更新密码</el-button
                        >
                    </el-form-item>
                </el-form>
            </el-card>
        </div>
    </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { getUserInfo } from '@/api/user'
import { User } from '@element-plus/icons-vue'

const userInfo = ref({})
const loading = ref(false)
const passwordLoading = ref(false)

// 表单引用
const formRef = ref(null)
const passwordFormRef = ref(null)

// 个人信息表单
const form = reactive({
    userName: '',
    accountId: '',
    email: '',
    phone: ''
})

// 密码表单
const passwordForm = reactive({
    currentPassword: '',
    newPassword: '',
    confirmPassword: ''
})

// 表单验证规则
const rules = {
    userName: [
        { required: true, message: '请输入用户名', trigger: 'blur' },
        { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
    ],
    email: [
        {
            pattern: /^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)+$/,
            message: '请输入正确的邮箱格式',
            trigger: 'blur'
        }
    ],
    phone: [
        {
            pattern: /^1[3-9]\d{9}$/,
            message: '请输入正确的手机号码',
            trigger: 'blur'
        }
    ]
}

// 密码验证规则
const passwordRules = {
    currentPassword: [
        { required: true, message: '请输入当前密码', trigger: 'blur' },
        { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
    ],
    newPassword: [
        { required: true, message: '请输入新密码', trigger: 'blur' },
        { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
    ],
    confirmPassword: [
        { required: true, message: '请再次输入新密码', trigger: 'blur' },
        {
            validator: (rule, value, callback) => {
                if (value !== passwordForm.newPassword) {
                    callback(new Error('两次输入的密码不一致'))
                } else {
                    callback()
                }
            },
            trigger: 'blur'
        }
    ]
}

// 获取用户信息
onMounted(async () => {
    try {
        const res = await getUserInfo()
        if (res.code === 200 && res.data) {
            userInfo.value = res.data

            // 填充表单
            form.userName = res.data.userName || ''
            form.accountId = res.data.accountId || ''
            form.email = res.data.email || ''
            form.phone = res.data.phone || ''
        }
    } catch (error) {
        console.error('获取用户信息失败', error)
    }
})

// 更新个人信息
const updateProfile = async () => {
    if (!formRef.value) return

    await formRef.value.validate(async (valid) => {
        if (valid) {
            loading.value = true

            try {
                // TODO: 调用更新用户信息的API
                // const res = await updateUserInfo(form)

                // 模拟API调用
                setTimeout(() => {
                    ElMessage.success('个人信息更新成功')
                    loading.value = false
                }, 1000)
            } catch (error) {
                console.error('更新个人信息失败', error)
                ElMessage.error('更新失败，请重试')
                loading.value = false
            }
        }
    })
}

// 更新密码
const updatePassword = async () => {
    if (!passwordFormRef.value) return

    await passwordFormRef.value.validate(async (valid) => {
        if (valid) {
            passwordLoading.value = true

            try {
                // TODO: 调用更新密码的API
                // const res = await updatePassword({
                //   oldPassword: passwordForm.currentPassword,
                //   newPassword: passwordForm.newPassword
                // })

                // 模拟API调用
                setTimeout(() => {
                    ElMessage.success('密码更新成功')
                    passwordLoading.value = false

                    // 清空密码表单
                    passwordForm.currentPassword = ''
                    passwordForm.newPassword = ''
                    passwordForm.confirmPassword = ''
                }, 1000)
            } catch (error) {
                console.error('更新密码失败', error)
                ElMessage.error('更新失败，请重试')
                passwordLoading.value = false
            }
        }
    })
}
</script>

<style scoped>
.page-container {
    padding: 20px;
    max-width: 1200px;
    margin: 0 auto;
}

.page-title {
    font-size: 24px;
    color: #333;
    margin-bottom: 20px;
    font-weight: normal;
}

.profile-container {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 20px;
}

.profile-card,
.password-card {
    height: fit-content;
}

.user-header {
    display: flex;
    align-items: center;
    margin-bottom: 20px;
}

.user-avatar {
    background: #4086f4;
    color: #fff;
    margin-right: 20px;
}

.user-info h2 {
    font-size: 18px;
    color: #333;
    margin: 0 0 5px 0;
    font-weight: normal;
}

.user-info p {
    color: #666;
    margin: 0;
}

.card-header h2 {
    font-size: 18px;
    color: #333;
    margin: 0;
    font-weight: normal;
}

.profile-form,
.password-form {
    margin-top: 20px;
}

@media (max-width: 768px) {
    .profile-container {
        grid-template-columns: 1fr;
    }
}
</style>
